package com.pack;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ListViewActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final Intent intentUpgrade=new Intent(this, UpgradeActivity.class);
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.listitem, R.id.listItemTextView);
		dbAdapter=new DbAdapter(this);
		dbAdapter.open();
		Cursor cursor=dbAdapter.getAllContacts();		
		dbAdapter.close();		
		while(cursor.moveToNext()) {			
			arrayAdapter.add(cursor.getString(1)+" "+cursor.getString(2));
		}
		if (!arrayAdapter.isEmpty()) {
			setContentView(R.layout.list);
			ListView listView = (ListView) findViewById(R.id.miaLista);
			listView.setAdapter(arrayAdapter);
			listView.setOnItemClickListener(new OnItemClickListener() {
				
				public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
					dbAdapter.open();
					Cursor cursor=dbAdapter.getAllContacts();
					dbAdapter.close();
					cursor.move(position+1);
					Bundle bundle=new Bundle();
					bundle.putLong("_id", cursor.getLong(0));
					bundle.putString("nome", cursor.getString(1));
					bundle.putString("cognome", cursor.getString(2));
					bundle.putString("email", cursor.getString(3));	
					bundle.putString("numero", cursor.getString(4));
					intentUpgrade.putExtras(bundle);
					startActivity(intentUpgrade);				
				}
			});						
		}else 
			setContentView(R.layout.emptylist);
		
		Button buttonIndietro=(Button)findViewById(R.id.buttonIndietro);
    	buttonIndietro.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				Intent intentMain=new Intent(getApplicationContext(), MainActivity.class);
				startActivity(intentMain);				
			}
		});
	}
	
	private DbAdapter dbAdapter;
}
